package com.linxz.framework.base.module;

import com.linxz.framework.base.ActivityLifeCycleEvent;
import com.linxz.framework.base.RxHelper;
import com.linxz.framework.protocol.callback.HttpCallBack;
import com.linxz.framework.protocol.retrofit.HttpStore;
import com.linxz.framework.protocol.retrofit.LinxzHttpCreator;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Set;
import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.subjects.PublishSubject;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @author Linxz
 * 创建日期：2019年02月20日 19:54
 * version：1.0.0
 * 描述：
 */
public class BaseModel {
    public static final HttpStore API_STORE;
    public PublishSubject<ActivityLifeCycleEvent> lifecycleSubject;

    static {
        API_STORE= LinxzHttpCreator.getHttpStore();
    }
    public BaseModel(PublishSubject<ActivityLifeCycleEvent> lifecycleSubject){
        this.lifecycleSubject=lifecycleSubject;
    }

    public static <T> T getOutApiStore(final Class<T> service){
        return LinxzHttpCreator.getOutApiStore(service);
    }

    /**RXjava取消注册，以避免内存泄露*/
    public void onUnsubscribe() {
    }

    /**
     * 将map集合转化为json串
     */
    public static RequestBody setJsonString(Map<String,Object> body){
        Set keys = body.keySet();
        JSONObject requestData = new JSONObject();
        for (Object key : keys) {
            Object value = body.get(key);
            try {
                requestData.put((String) key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return RequestBody.create(MediaType.parse("application/json"),requestData.toString());
    }


    /**
     * 添加线程管理并订阅
     * @param ob:网络请求被观察者
     * @param subscriber:结果监听
     */
    public void toSubscribe(Observable ob, final HttpCallBack subscriber) {
        ObservableTransformer<String, Object> result = RxHelper.handleResult(ActivityLifeCycleEvent.DESTROY, lifecycleSubject);
        Observable observable = ob.compose(result);
        observable.subscribe(subscriber);
    }
}
